package one.stand.controller;

import com.jmp.api.crm.dto.WebsiteResponse;
import com.jmp.api.crm.dto.WebsiteSaveRequest;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import io.swagger.annotations.ApiOperation;
import one.stand.model.Company;
import one.stand.model.ResultModel;
import one.stand.model.Website;
import one.stand.service.CompanyBaseService;
import one.stand.service.WebsiteService;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("crmPc/website")
public class WebsiteController {
    @Autowired
    private WebsiteService websiteService;
    @Autowired
    private CompanyBaseService companyBaseService;

    @ApiOperation(value = "官网信息")
    @PostMapping("")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<WebsiteResponse> info() {
        final Integer userCompanyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        Website website = websiteService.getByCompanyId(userCompanyId);
        Company company = companyBaseService.getById(userCompanyId);
        WebsiteResponse response = WebsiteResponse.builder()
                .companyIntroduce(website.getCompanyIntroduce())
                .showRoomState(company.getShowroomstate())
                .photos(StringUtils.isNoneBlank(website.getPhotos()) ? website.getPhotos().split(",") : null)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "保存")
    @PostMapping("save")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel save(@RequestAttribute WebsiteSaveRequest request) {
        final Integer userCompanyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        Website website = websiteService.getByCompanyId(userCompanyId);

        Website websiteUpdate = new Website();
        websiteUpdate.setWebsiteId(website.getWebsiteId());
        websiteUpdate.setCompanyIntroduce(request.getCompanyIntroduce());
        websiteUpdate.setPhotos(Objects.nonNull(request.getPhotos()) ? StringUtils.join(request.getPhotos(), ",") : null);
        companyBaseService.updateShowRoomStateById(userCompanyId, request.getShowRoomState());
        websiteService.update(websiteUpdate);

        return ResultModel.success();
    }
}
